package com.inventory.service.impl;

import com.inventory.model.Product;
import com.inventory.model.SaleRecord;
import com.inventory.repository.SaleRecordRepository;
import com.inventory.service.ProductService;
import com.inventory.service.SaleRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class SaleRecordServiceImpl implements SaleRecordService {

    @Autowired
    private SaleRecordRepository saleRecordRepository;
    
    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public SaleRecord saveSaleRecord(SaleRecord saleRecord) {
        // 检查库存是否足够
        Product product = saleRecord.getProduct();
        if (product.getQuantity() < saleRecord.getQuantity()) {
            throw new RuntimeException("库存不足，无法完成销售");
        }
        
        // 保存销售记录
        SaleRecord savedRecord = saleRecordRepository.save(saleRecord);
        
        // 更新商品库存（减少）
        productService.updateStock(product.getId(), -saleRecord.getQuantity());
        
        return savedRecord;
    }

    @Override
    @Transactional
    public void deleteSaleRecord(Long id) {
        Optional<SaleRecord> saleOpt = saleRecordRepository.findById(id);
        if (saleOpt.isPresent()) {
            SaleRecord sale = saleOpt.get();
            
            // 删除销售记录前，恢复相应的商品库存
            productService.updateStock(sale.getProduct().getId(), sale.getQuantity());
            
            // 删除记录
            saleRecordRepository.deleteById(id);
        }
    }

    @Override
    public Optional<SaleRecord> findById(Long id) {
        return saleRecordRepository.findById(id);
    }

    @Override
    public List<SaleRecord> findAllSaleRecords() {
        return saleRecordRepository.findAll();
    }

    @Override
    public List<SaleRecord> findByProductId(Long productId) {
        return saleRecordRepository.findByProductId(productId);
    }

    @Override
    public List<SaleRecord> findByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return saleRecordRepository.findBySaleDateBetween(startDate, endDate);
    }

    @Override
    public Double getTotalSaleAmount(LocalDateTime startDate, LocalDateTime endDate) {
        Double amount = saleRecordRepository.getTotalSaleAmountBetween(startDate, endDate);
        return amount != null ? amount : 0.0;
    }

    @Override
    public Double getTotalProfit(LocalDateTime startDate, LocalDateTime endDate) {
        Double profit = saleRecordRepository.getTotalProfitBetween(startDate, endDate);
        return profit != null ? profit : 0.0;
    }

    @Override
    public List<SaleRecord> findLatestSalesByProductId(Long productId) {
        return saleRecordRepository.findLatestSalesByProductId(productId);
    }

    @Override
    public List<Map<String, Object>> findTopSellingProducts(LocalDateTime startDate, LocalDateTime endDate, int limit) {
        List<Object[]> results = saleRecordRepository.findTopSellingProducts(startDate, endDate);
        List<Map<String, Object>> topProducts = new ArrayList<>();
        
        int count = 0;
        for (Object[] result : results) {
            if (count >= limit) break;
            
            Long productId = (Long) result[0];
            Long totalQuantity = (Long) result[1];
            
            Optional<Product> productOpt = productService.findById(productId);
            if (productOpt.isPresent()) {
                Product product = productOpt.get();
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("id", product.getId());
                productMap.put("name", product.getName());
                productMap.put("totalQuantity", totalQuantity);
                topProducts.add(productMap);
                count++;
            }
        }
        
        return topProducts;
    }
} 